package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Auction-Server, used to listen for Auction-Clients.
 * Users can create Auctions, list Auctions and bid on Auctions.
 * The Server listenes for Messages via TCP and answers to them.
 * The Server is also listening sending UDP-Messages to the client.
 * @author Andreas Mair
 */
public class Server 
implements Runnable 
{
	private ServerSocket serverSocket; 
	private int iPort;
	private List<Socket>clientSockets; 
	private ExecutorService executor;
	private boolean bStopped=false;
	/**
	 * Constructor creates a new Server and runs it
	 * @param port
	 */
	public Server(String port) throws NumberFormatException
	{
		this.iPort=Integer.parseInt(port);
		this.clientSockets=new ArrayList<Socket>();
		executor=Executors.newCachedThreadPool();
	}
	
	@Override
	public void run() 
	{
		try 
		{
		    serverSocket = new ServerSocket(iPort);
			while(!bStopped)
			{
	            Socket clientSocket = serverSocket.accept();
	            clientSockets.add(clientSocket);
	            executor.execute(new TCPServerThread(clientSocket));
			}	
		} 
		catch (IOException e) 
		{
		    System.out.println("IOException occured while waiting for Clients "+e.getMessage());
		}
		finally
		{
			stop();
		}
		System.out.println("Server-Main-Thread stops...");
	}
	
	
	public void stop()
	{
		if(!bStopped)
		{
			bStopped=true;
			try 
			{
				if(serverSocket!=null && !serverSocket.isClosed())
				{
					serverSocket.close();
				}
			} catch (IOException e1) {

				//ignore
			}
			//close all client-connections
	        for(Socket s:clientSockets)
	        {
	        	if(!s.isClosed())
	        	{
	        		try 
	        		{
						s.close();
					}
	        		catch (IOException e) 
					{
						//ignore
					}
	        	}
	        }
	        if(executor!=null)
	        {
	        	executor.shutdown();
	        	executor.shutdownNow();
	        }
	        AuctionManager.getInstance().stopTimer();
		}
	}
}
